package other;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @description：
 * @author： HD
 * @time：2017/8/29
 */

public class UDPClient implements Runnable {

    private DatagramSocket mDatagramSocket;

    private InetAddress mInetAddress;

    private int mPort;

    private String mIP;

    public UDPClient(String ip, int port) {
        mIP = ip;
        mPort = port;
    }

    @Override
    public void run() {

        try {

            mDatagramSocket = new DatagramSocket();
            mInetAddress = InetAddress.getByName(mIP);

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


        // 接收UDP广播，有的手机不支持
        while (true) {
            byte[] recbuf = new byte[1024];
            DatagramPacket recpacket = new DatagramPacket(recbuf, recbuf.length);
            try {
                mDatagramSocket.receive(recpacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.i("Server: Message received: ‘" + new String(recpacket.getData()) + "’\n");
            LogUtils.i("Server: IP " + recpacket.getAddress() + "’\n");
        }
    }


    public void sendData(String data) {

        /*
         * 在Java UDP中单播与广播的代码是相同的,要实现具有广播功能的程序只需要使用广播地址即可, 例如：这里使用了本地的广播地址
         */
        try {

            byte[] msg = data.getBytes();

            DatagramPacket datagramPacket = new DatagramPacket(msg, msg.length, mInetAddress, mPort);

            mDatagramSocket.send(datagramPacket);
            LogUtils.i("Client send msg complete: " + data);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void close() {
        mDatagramSocket.close();
    }

}
